package com.tools.hry.xls.create.util;

import com.tools.hry.xls.create.DataSet;
import com.tools.hry.xls.create.rule.ExcelStyle;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.OutputStream;
import java.util.List;

/**
 * Created by 峥桂 on 2017/9/6.
 */
public class WriteExcelUtils {
    private static String EXCEL_2003 = ".xls";
    private static String EXCEL_2007 = ".xlsx";
    private static ExcelStyle excelStyle;


    private static void _init(Workbook workbook,DataSet dataSet){
        boolean templateName2007=false;
        if(workbook instanceof XSSFWorkbook){
            templateName2007=true;
        }else {
            templateName2007=false;
        }
        excelStyle=new ExcelStyle(dataSet.getSelfTemplatePath(),templateName2007);
        excelStyle.initStyle(workbook);
    }


    /**
     * 将数据写入到Excel文件中
     * @param outputStream
     * @param dataSet
     * @throws Exception
     */
    public static void writeExcelPOIToIo(DataSet dataSet,String fileName,
                                                 OutputStream outputStream)throws Exception{
        //写入到文件输出流中
        Workbook workbook=writeExcelPOI(fileName,dataSet);
        workbook.write(outputStream);
    }

    public static Workbook writeExcelPOI(String fileName,DataSet dataSet)throws Exception{
        Workbook workbook = null;
        if (StringUtils.isNotBlank(fileName)) {

            if (fileName.toLowerCase().endsWith(EXCEL_2003)) {
                workbook = new HSSFWorkbook();
            }
            if (fileName.toLowerCase().endsWith(EXCEL_2007)) {
                workbook = new XSSFWorkbook();
            }
            if(workbook==null){
                throw new RuntimeException("创建excel失败，请检查文件名后缀是否正确！");
            }
            // 创建sheet对象
            Sheet sheet1 = workbook.createSheet("sheet1");
            if (dataSet!=null) {
                _init(workbook,dataSet);
                int headerNum = 0;
                int rowNum = 1;
                if (dataSet.isNeedTitle()) {//是否需要标头
                    headerNum = 1;
                    rowNum = 2;
                    _createTitle(sheet1, new String[]{dataSet.getTitleName(), dataSet.getActionName(),
                        dataSet.getCreateTime()}, 0, dataSet.getHeaders().length);
                }
                _createHeader(sheet1, dataSet.getHeaders(), headerNum,dataSet.isNeedStyle());
                List<String[]> dataList = dataSet.getDataList();
                //循环数据将写入Excel中
                int listSize = dataList.size();Row row ; Cell cell; String[] columns;
                for (int i = 0; i < listSize; i++) {
                    row= sheet1.createRow(rowNum);
                    rowNum++;
                    columns = dataList.get(i);
                    for (int j = 0; j < columns.length; j++) {
                        cell= row.createCell(j);
                        cell.setCellValue(columns[j]);
                        if(dataSet.isNeedStyle()){
                            cell.setCellStyle(excelStyle.getContentStyle());
                        }
                        sheet1.setColumnWidth(j,_getWidthValue());
                    }
                }
            }
        }
        return workbook;
    }

    private static  int _getWidthValue(){
        return "空值".getBytes().length*3*256;
    };

    private static void  _createTitle(Sheet sheet1, String[] titles,int rowNum,int headerLength){
        Row row = sheet1.createRow(rowNum);
        _buildCell(row,0,"标题：",excelStyle.getTitleStyle());
        _buildCell(row,1,titles[0],excelStyle.getTitleStyle_());
        _buildCell(row,3,"创建者：",excelStyle.getTitleStyle());
        _buildCell(row,4,titles[1],excelStyle.getTitleStyle_1());
        _buildCell(row,6,"创建时间：",excelStyle.getTitleStyle());
        _buildCell(row,7,titles[2],excelStyle.getTitleStyle_2());

        if(headerLength>=9){
            CellRangeAddress region = new CellRangeAddress(rowNum, rowNum, 1, 2); // 参数都是从O开始
            sheet1.addMergedRegion(region);
            region = new CellRangeAddress(rowNum, rowNum, 4, 5); // 参数都是从O开始
            sheet1.addMergedRegion(region);
            region = new CellRangeAddress(rowNum, rowNum, 7, 8); // 参数都是从O开始
            sheet1.addMergedRegion(region);
        }

    }
    private static void  _createHeader(Sheet sheet1, String[] headers,int rowNum,boolean isNeedStyle){
        Row row = sheet1.createRow(rowNum);
        for (int j = 0; j < headers.length; j++) {
            _buildCell(row,j,headers[j],isNeedStyle==true?excelStyle.getHeaderStyle():null);
        }
    }

    private static void _buildCell(Row row,int rowIndex,String object,CellStyle cellStyle){
        Cell cell = row.createCell(rowIndex);
        cell.setCellValue(object);
        if(cellStyle!=null){
            cell.setCellStyle(cellStyle);
        }
    }


}
